package com.intel.bluetooth;

import com.medlinx.vstp.EcgLead;
import com.medlinx.vstp.VstpDataType;
import com.mlnx.constant.SystemConstant;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class MultiChannelBufferBT {

	private DecimalFormat df = new DecimalFormat("#.000");
	private static final String TAG = "MultiChannelBufferBT";
	private int frequency = 300;
	private boolean frequencyChange = false;
	private int secondBuffer = 20;
	private ArrayList<int[]> bufferList;

	private int currentIndex;
	private VstpDataType dataType = VstpDataType.UNKNOWN;

	long startT, lastT;

	private RandomAccessFile raf = null;

	public MultiChannelBufferBT() {
		int MaxElements = frequency * secondBuffer;
		currentIndex = 0;

		startT = 0;
		// connectStr = "http://localhost:8787";
		// create and initialize mutli-channel buffer
		bufferList = new ArrayList<int[]>();
		for (int indexC = 0; indexC < 12; ++indexC) {
			int[] tempIntArray = new int[MaxElements];
			for (int j = 0; j < secondBuffer; ++j) {
				int startP = j * frequency;
				for (int i = startP; i < (startP + frequency); ++i) {
					tempIntArray[i] = 32768;

				}
			}
			bufferList.add(tempIntArray);
		}
	}

	public ArrayList<int[]> getBufferList() {
		return bufferList;
	}

	public int getLocalMeanChannel(int start, int width, int Channel) {
		int maxElement = frequency * secondBuffer;
		if (start < 0)
			start += maxElement;
		start = start % (maxElement);
		int meanV = 0;
		for (int i = start; i < (start + width); ++i) {
			meanV += bufferList.get(Channel)[i % maxElement];
		}
		return meanV / width;
	}

	public boolean isRunning() {
		long cur = System.currentTimeMillis();
		if (cur - lastT > 5000)
			return false;
		return true;
	}

	public int getFrequency() {
		return frequency;
	}

	public void setFrequency(int _frequency) {
		frequency = _frequency;
		currentIndex = 0;
		frequencyChange = true;
	}

	public boolean isFrequencyChange() {
		boolean isChange = frequencyChange;
		frequencyChange = false;
		return isChange;
	}

	public int getTimeWindow() {
		return secondBuffer;
	}

	public void putECGDataBuffer(int[][] buffer) {
		lastT = System.currentTimeMillis();
		for (int[] block : buffer) {
			putECGDataBuffer(block);

			currentIndex++;
			currentIndex = currentIndex % (frequency * secondBuffer);
		}
	}

	private void putECGDataBuffer(int[] block) {
		// if(Math.abs(block[0]) < 30000)
		// Log.v(TAG, "block value " + block[0]);
		// Log.v(TAG, "current index " + currentIndex);
		switch (dataType) {
		case ECG_1CH:
			bufferList.get(0)[currentIndex] = block[0];
			break;
		case ECG_3CH:
			bufferList.get(0)[currentIndex] = block[0];
			bufferList.get(1)[currentIndex] = block[1];
			bufferList.get(2)[currentIndex] = EcgLead.derive(EcgLead.III,
					block[0], block[1]);
			bufferList.get(3)[currentIndex] = EcgLead.derive(EcgLead.aVR,
					block[0], block[1]);
			bufferList.get(4)[currentIndex] = EcgLead.derive(EcgLead.aVL,
					block[0], block[1]);
			bufferList.get(5)[currentIndex] = EcgLead.derive(EcgLead.aVF,
					block[0], block[1]);
			bufferList.get(6)[currentIndex] = block[2];
			break;
		case ECG_8CH:
			StringBuffer sb = new StringBuffer();
			sb.append(df.format(SystemConstant.ECGConvertor(block[0])) + ", ");
			sb.append(df.format(SystemConstant.ECGConvertor(block[1])) + ", ");
			sb.append(df.format(SystemConstant.ECGConvertor(EcgLead.derive(
					EcgLead.III, block[0], block[1]))) + ", ");
			sb.append(df.format(SystemConstant.ECGConvertor(EcgLead.derive(
					EcgLead.aVR, block[0], block[1]))) + ", ");
			sb.append(df.format(SystemConstant.ECGConvertor(EcgLead.derive(
					EcgLead.aVL, block[0], block[1]))) + ", ");
			sb.append(df.format(SystemConstant.ECGConvertor(EcgLead.derive(
					EcgLead.aVF, block[0], block[1]))) + ", ");
			sb.append(df.format(SystemConstant.ECGConvertor(block[2])) + ", ");
			sb.append(df.format(SystemConstant.ECGConvertor(block[3])) + ", ");
			sb.append(df.format(SystemConstant.ECGConvertor(block[4])) + ", ");
			sb.append(df.format(SystemConstant.ECGConvertor(block[5])) + ", ");
			sb.append(df.format(SystemConstant.ECGConvertor(block[6])) + ", ");
			sb.append(df.format(SystemConstant.ECGConvertor(block[7])));
			saveData(sb.toString());
			break;
		default:
			System.err.println(TAG + "：number of channels is invalid:"
					+ dataType.getNumberOfChannels());
		}
	}

	public int getCurrentPT() {
		return currentIndex;
	}

	public int getSecondBuffer() {
		return secondBuffer;
	}

	public void setSecondBuffer(int _secondBuffer) {
		secondBuffer = _secondBuffer;
	}

	public void setDataType(VstpDataType dataType) {
		this.dataType = dataType;
	}

	public RandomAccessFile getRaf() {
		if (raf == null) {
			String currPath = System.getProperty("user.dir");
			File file = new File(currPath + File.separator + "bpDeviceData.txt");

			if (!file.exists()) {
				try {
					file.createNewFile();
					raf = new RandomAccessFile(file, "rw");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return raf;
	}

	public void saveData(String str) {
		try {
			getRaf().writeBytes(str);
			getRaf().writeBytes("\r\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
